package com.product.aspect;

import com.common.VO.SysResult;
import com.common.domain.Product;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.product.service.SearchService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.CodeSignature;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Elias
 * @version 1.0
 * @date 2021-05-12 9:53
 * @description
 * @copyright 2021
 */
@Component
@Aspect
public class ProductIndex {
    @Resource
    private SearchService searchService;

    /**
     * 增加商品后需要同步更新索引
     * @param jp 连接点
     * @param result 返回值
     * @throws JsonProcessingException 抛出
     */
    @AfterReturning(value = "execution(* com.product.service.ProductService*.addProduct(..))",returning = "result")
    public void afterAddProduct(JoinPoint jp,Object result)throws JsonProcessingException{
        Map<String, Object> map = new HashMap<>();
        String[] names = ((CodeSignature)jp.getSignature()).getParameterNames();
        Object[] values = jp.getArgs();
    for (int i = 0; i < names.length; i++) {
      map.put(names[i],values[i]);
    }
        Product product = (Product) map.get("product");
        SysResult addResult = this.searchService.addProduct(product);
    }


    /**
     * 更新商品后需要同步更新索引，先删后增
     * @param jp 连接点
     * @param result 返回值
     * @throws JsonProcessingException 抛出
     */
    @AfterReturning(value = "execution(* com.product.service.ProductService*.updateProduct(..))",returning = "result")
    public void afterUpdateProduct(JoinPoint jp,Object result) throws JsonProcessingException{
Map<String, Object> map = new HashMap<>();
String[] names = ((CodeSignature)jp.getSignature()).getParameterNames();
Object[] values = jp.getArgs();
for(int i = 0; i < names.length; i++) {
    map.put(names[i], values[i]);
}
Product product = (Product) map.get("product");
SysResult deleteResult = this.searchService.deleteProduct(product);
this.afterAddProduct(jp,result);
    }
}
